﻿import {useState, useEffect, useRef} from 'react';
import * as THREE from 'three';
import {gsap} from 'gsap';
import './ToTop.css';

function ToTop() {
    const [isVisible, setIsVisible] = useState(false);
    const toTopRef = useRef<HTMLDivElement>(null);
    const sceneRef = useRef<THREE.Scene | null>(null);
    const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
    const rendererRef = useRef<THREE.WebGLRenderer | null>(null);
    const buttonMeshRef = useRef<THREE.Mesh | null>(null);
    const animateId = useRef<number | null>(null);
    
    // 初始化Three.js 场景
    const initThreeScene = () => {
        if (!toTopRef.current) return null;
        
        const container = toTopRef.current.querySelector('#three-container') as HTMLDivElement;
        if (!container) return null;
        
        // 场景基础配置
        const scene = new THREE.Scene();
        const camera = new THREE.PerspectiveCamera(
            75,
            container.clientWidth / container.clientHeight,
            0.1,
            1000
        );
        const renderer = new THREE.WebGLRenderer({
            alpha: true,
            antialias: true
        });
        
        // 渲染器设置
        renderer.setSize(80, 80);
        renderer.setPixelRatio(window.devicePixelRatio);
        container.appendChild(renderer.domElement);
        
        // 光照系统
        const ambientLight = new THREE.AmbientLight(0x000000, 0.5);
        const directionalLight = new THREE.DirectionalLight(0x000000, 0.8);
        directionalLight.position.set(5, 5, 5);
        scene.add(ambientLight, directionalLight);
        
        return {scene, camera, renderer};
    };
    
    // 创建3D按钮
    const createButton = (scene: THREE.Scene) => {
        // 几何体组合
        const geometry = new THREE.IcosahedronGeometry(1.5, 2);
        const material = new THREE.MeshPhongMaterial({
            color: 0x00eb861a, // 主色调改为橙色
            specular: 0xffffff, // 调整高光颜色增强金属质感
            shininess: 120,
            transparent: true,
            opacity: 0.95
        });
        
        // 主按钮体
        const buttonMesh = new THREE.Mesh(geometry, material);
        
        // 边缘高光
        const edges = new THREE.EdgesGeometry(geometry);
        const lineMaterial = new THREE.LineBasicMaterial({
            color: 0xffffff,
            linewidth: 2
        });
        const wireframe = new THREE.LineSegments(edges, lineMaterial);
        buttonMesh.add(wireframe);
        
        scene.add(buttonMesh);
        return buttonMesh;
    };
    
    // 滚动监听
    useEffect(() => {
        const handleScroll = () => {
            setIsVisible(window.scrollY > 300);
            
            const canvas = document.querySelector('#three-container canvas') as HTMLCanvasElement;
            if (!canvas) return;
            
            // 获取当前视图位置
            const scrollPosition = window.scrollY;
            canvas.style.transition = 'top 0.5s ease';
            if (scrollPosition > 0) {
                // 如果大于0，按钮向上移动
                canvas.style.top = '40px';
            } else {
                canvas.style.top = '0px';
            }
        };
        
        window.addEventListener('scroll', handleScroll);
        return () => window.removeEventListener('scroll', handleScroll);
    }, []);
    
    // Three.js 初始化
    useEffect(() => {
        const threeScene = initThreeScene();
        if (!threeScene) return;
        
        const {scene, camera, renderer} = threeScene;
        sceneRef.current = scene;
        cameraRef.current = camera;
        rendererRef.current = renderer;
        camera.position.z = 5;
        
        // 创建按钮
        buttonMeshRef.current = createButton(scene);
        
        // 动画循环
        const animate = () => {
            if (buttonMeshRef.current) {
                buttonMeshRef.current.rotation.x += 0.005;
                buttonMeshRef.current.rotation.y += 0.005;
            }
            if (renderer && scene && camera) {
                renderer.render(scene, camera);
            }
            animateId.current = requestAnimationFrame(animate);
        };
        animate();
        
        // 响应式处理
        const handleResize = () => {
            if (!toTopRef.current || !camera || !renderer) return;
            
            const container = toTopRef.current.querySelector('#three-container') as HTMLDivElement;
            if (!container) return;
            
            camera.aspect = container.clientWidth / container.clientHeight;
            camera.updateProjectionMatrix();
            renderer.setSize(container.clientWidth, container.clientHeight);
        };
        
        window.addEventListener('resize', handleResize);
        
        return () => {
            if (animateId.current) cancelAnimationFrame(animateId.current);
            if (renderer) renderer.dispose();
            window.removeEventListener('resize', handleResize);
        };
    }, []);
    
    // 交互处理
    const handleHover = (isHover: boolean) => {
        if (!buttonMeshRef.current) return;
        // @ts-ignore
        gsap.to(buttonMeshRef.current.material.color, {
            r: isHover ? 1.0 : 0.921,
            g: isHover ? 0.655 : 0.525,
            b: isHover ? 0.149 : 0.102,
            duration: 0.3
        });
    };
    
    const handleClick = () => {
        if (!buttonMeshRef.current) return;
        gsap.timeline()
            .to(buttonMeshRef.current.scale, {
                x: 0.8,
                y: 0.8,
                z: 0.8,
                duration: 0.2
            })
            .to(buttonMeshRef.current.position, {
                y: -1,
                duration: 0.2
            })
            .to(buttonMeshRef.current.scale, {
                x: 1,
                y: 1,
                z: 1,
                duration: 0.2,
                ease: 'elastic.out(1.2, 0.3)'
            })
            .to(buttonMeshRef.current.position, {
                y: 0,
                duration: 0.5
            });
        
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    };
    
    return (
        <div
            ref={toTopRef}
            className={`to-top border border-primary fixed md:right-32 right-12
        ${isVisible ? 'translate-y-0 h-72' : '-translate-y-full h-0 -top-8'}`}
            style={{zIndex: 9, transition: 'all 0.5s cubic-bezier(0.4, 0, 0.2, 1)'}}
        >
            <div
                id="three-container"
                className="absolute bottom-0 left-1/2 -translate-x-1/2 w-20 h-20 cursor-pointer"
                onMouseEnter={() => handleHover(true)}
                onMouseLeave={() => handleHover(false)}
                onClick={handleClick}
            />
        </div>
    );
}

export default ToTop;